<template>

  <el-dialog title="选择物料" :visible="selectDialog" width="70%" class="matrial-dialog-box" @close="selectClose">
    <div class="matrial-box">
      <div class="app-container basicfile-box">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="6" :md="6" :lg="4">
            <!-- 分类数据 -->
            <Tree ref="tree" :sortTree="sortTree" :isHeight="isHeight" :loading="loading" :isOperation="isOperation"
              @nodeClick="nodeClick(arguments)" />
          </el-col>
          <!-- 搜索数据 -->
          <el-col :span="20" :xs="24">
            <el-form :inline="true" class="ma-search"  label-width="68px" style="margin-bottom: 8px;">
              <div class="ma-left">
              <el-form-item label="物料编码">
                <el-input v-model="searchForm.searchCode" clearable size="small" style="width: 240px" />
              </el-form-item>
              <el-form-item label="物料名称">
                <el-input v-model="searchForm.searchName" clearable size="small" style="width: 240px" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" @click="search" size="mini">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="serchReset()">重置</el-button>
              </el-form-item>
              </div>
              <div class="ma-right">
                <el-button type="primary" plain icon="el-icon-menu" size="mini" @click="checkleAll">查询所有</el-button>


                <el-button type="primary" plain icon="el-icon-menu" :class="{'is-plan':continuityStatus}" size="mini"
                  @click="handleContinuity">连选
                </el-button>

              </div>

            </el-form>
            <el-row :gutter="10" class="mb8 operation-btn">
              <div style="display: flex;justify-content:space-between;width: 100%;">

              </div>
            </el-row>
            <!-- 物料数据 -->
            <el-table :row-class-name="tableRowClassName" v-loading="loading" :data="basicfileList" :height="maxHeight"
              border @row-dblclick="handleSelect">
              <el-table-column label="物料编码" align="center" sortable prop="code">
              </el-table-column>
              <el-table-column label="物料名称" align="center" prop="name" sortable @click.stop="seeMaterial(scope.row)">
              </el-table-column>
              <el-table-column label="型号规格" align="center" prop="attribute" />
              <el-table-column label="主计量" align="center" prop="unitName" width="75" />
              <el-table-column label="操作" align="center" class-name="small-padding" width="220">
                <template slot-scope="scope">
                  <div class="public-btn">
                    <el-button size="mini" type="text" @click.stop="handleSelect(scope.row,scope.$index)">选择
                    </el-button>
                    <el-button size="mini" type="text" class="basic-see" @click.stop="seeMaterial(scope.row)">查看
                    </el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页信息 -->
            <pagination v-show="total>21" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
              @pagination="getMaterialList" />
          </el-col>
        </el-row>

        <!-- 新增/查看/修改物料弹框信息 -->
        <el-dialog :title="dialogTitle" :visible.sync="open" width="600px" v-if="open" @close='closeDialog'
          append-to-body class="material-in-dialog">
          <el-form ref="materialForm" :model="materialForm" label-width="80px" size="medium" disabled
            :validate-on-rule-change="false" :hide-required-asterisk="star">
            <el-row>
              <el-col :span="24">
                <el-form-item label="分类信息" prop="value">
                  <el-cascader v-model="value" :options="sortTree" ref="classTree" :props="classProps" class="cas-input"
                   ></el-cascader>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="物料编码">
                  <el-input v-model="materialForm.code" :disabled="true"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="更新时间">
                  <el-input v-model="materialForm.updateTime" class="updata-time"></el-input>
                </el-form-item>
              </el-col>
              <!-- 左部开始 -->
              <el-col :span="12">
                <el-col :span="24">
                  <el-form-item label="物料名称" prop="name">
                    <el-input v-model="materialForm.name"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="主计量" prop="packingForm">
                    <el-select v-model="packingForm" placeholder="请选择">
                      <el-option v-for="(item,index) in packingDate" :key="index" :label="item.name" :value="item.code">
                        <span>{{ item.name }}</span>
                        <span>（{{ item.code }}）</span>
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="型号规格" prop="attribute">
                    <el-input v-model="materialForm.attribute"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="规格描述" prop="property">
                    <el-input v-model="materialForm.property"></el-input>
                  </el-form-item>
                </el-col>
              </el-col>
              <!-- 左部结束 -->
              <!-- 右部开始 -->
              <el-col :span="12">
                <div style="overflow: hidden;margin-right: 10px;">
                  <div class="ma-right">
                    <el-col :span="24">
                      <el-form-item label="启用批号" prop="enableBatch" style="text-align: right;">
                        <el-switch v-model="materialForm.enableBatch" active-value="1" inactive-value="0"></el-switch>
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="发料有零头" prop="enableChip" style="text-align: right;">
                        <el-switch v-model="materialForm.enableChip" active-value="1" inactive-value="0"></el-switch>
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="允许负库存" prop="enableDebt" style="text-align: right;">
                        <el-switch v-model="materialForm.enableDebt" active-value="1" inactive-value="0"></el-switch>
                      </el-form-item>
                    </el-col>
                  </div>
                </div>
              </el-col>
              <!-- 右部结束 -->
            </el-row>
          </el-form>
          <!-- 物料数量表单 -->
          <div class="from-mount" >
            <el-form :model="materialMount" label-width="100px" size="medium" class="mount-form"
              disabled>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="当前库存数量" class="txt-right">
                    <el-input v-model="materialMount.quantity" class="now-stock"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="实际可用数量" class="txt-right">
                    <el-input v-model="materialMount.available" class="now-actual"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="计划锁定数量">
                    <el-input v-model="materialMount.mp" class="txt-right"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="销售锁定数量">
                    <el-input v-model="materialMount.om" class="txt-right"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="采购在途数量">
                    <el-input v-model="materialMount.po" class="txt-right"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="生产在途数量" class="txt-right">
                    <el-input v-model="materialMount.prs"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="委外在途数量" class="txt-right">
                    <el-input v-model="materialMount.pu"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>


        </el-dialog>
      </div>
    </div>
  </el-dialog>
</template>

<script>
  import {
    getToken
  } from "@/utils/auth";
  import {
    listSort,
  } from "../../api/sort"; //分类接口
  import {
    listMaterial,
    seeMaterial,
  } from "../../api/checkin"; //物料接口
  import {
    getTreeData,
    getEcho,
  } from "../../utils/items" //js方法
  import Tree from "../../components/Sort/tree"; //分类组件
  export default {
    name: "Items",
    data() {
      return {
        // 遮罩层
        loading: true,
        //是否显示分类操作按钮
        isOperation: true,
        // 树形数据
        sortTree: [],
        //树形选中是否高亮
        isHeight: true,
        //物料数据最大高度
        maxHeight: null,
        number: 0,
        //搜索参数
        searchForm: {
          searchName: "", //搜索物料名称
          searchCode: "", //搜索物料编码
        },
        continuityStatus: false,
        // 头部物料搜索
        headerFrom: {
          codeInput: "",
          nameInput: ""
        },
        //头部编码输入框状态
        inputStatusCode: false,
        inputStatusName: false,
        // 物料查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 100,
          type: true,
          sortRoot: ""
        },
        serachSortId: [],
        // 总条数
        total: 0,
        // 物料数据
        basicfileList: [],
        // 新增/修改/编辑对话框状态
        open: false,
        //对话框标题
        dialogTitle: "",
        //必填是否显示*号
        star: false,
        //选择分类回显信息
        value: [],
        //分类选择配置
        classProps: {
          children: "children",
          label: "sortName",
          value: "sortCode",
          checkStrictly: true
        },
        packingDate: [],
        // 主计量
        packingForm: "",
        // 物料新增/修改信息表单
        materialForm: {
          code: "",
          sortId: "",
          name: "",
          attribute: "",
          initial: "",
          price: "",
          place: ""
        },
        //物料查看数量表单
        materialMount: {},
      }

    },
    props: {
      sortArrId: {
        type: Array,
        default: () => ([])
      },
      selectDialog: {
        type: Boolean,
        default: false
      }
    },
    created() {
      //隐藏操作按钮
      this.isOperation = false;
    },
    methods: {
      //弹框状态
      selectShow() {
        this.productNameShow = true;
      },

      handleContinuity() {
        this.continuityStatus = !this.continuityStatus;
        if(this.continuityStatus == false){
          this.basicfileList.forEach(value => {
            value.background = false;
          })
          // this.number = 0;
        }
      },

      /* 复制表格变色 */
      tableRowClassName({
        row,
        rowIndex
      }) {
        if (row.background === true) {
          return 'light-row';
        }
        return '';
      },

      // 选中物料
      handleSelect(row) {
        console.log(this.continuityStatus)
        if (this.continuityStatus == true) {
          row.background = true;
        }
        this.number++
        this.$emit("handleSelect", row, this.continuityStatus, this.number)

      },

      //获取分类数据
      getTreeList() {
        this.loading = true,
          listSort({
            feature: ""
          }).then(res => {
            let tree = res.data;
            let getArr = [],
              getSortId = [];
              this.serachSortId=[];
            if (this.sortArrId.length > 0) {
              this.sortArrId.forEach(id => {
                tree.forEach(item => {
                  if (id == item.sortId) {
                    getArr.push(item);
                    this.serachSortId.push(item.sortId);
                  }
                })
              })
              this.sortTree = getTreeData(getArr);
            } else {
              this.sortTree = getTreeData(res.data);
            }
            this.getMaterialList()

            this.loading = false;
          });
      },

      // 获取物料数据
      getMaterialList() {
         this.queryParams.sortRoot = "";
        if (this.serachSortId.length > 0) {
          let root = this.serachSortId.toString();
          this.queryParams.sortRoot = root;
        } else {
          this.queryParams.sortRoot = "";
        }
        listMaterial(this.queryParams).then(res => {
          let arrBasic = JSON.parse(JSON.stringify(res.rows));
          //数量格式化4位小说
          arrBasic.forEach(value => {
            value.background = false;
            value.initial = this.Decimal(value.initial);
            value.price = this.Decimal(value.price);
            value.amount = this.Decimal(value.amount);
          })
          this.basicfileList = arrBasic;
          this.total = res.total;
          this.maxHeight = (`${document.documentElement.clientHeight}` - 400);

        })
      },

      //获取主计量数据
      getPacking() {
        return new Promise((resolve, reject) => {
          listUnit().then(res => {
            if (res.code == 200) {
              this.packingDate = res.rows;
              resolve()
            }
          }).catch(err => {
            this.msgError("获取主计量失败！");
          })
        })

      },

      //物料分类点击获取
      nodeClick(node) {
        this.queryParams.name = ""; //避免当搜索物料信息时页面缓存物料名称
        this.queryParams.code = ""; //避免当搜索物料信息时页面缓存物料编码
        this.queryParams.type = true; //默认模糊查询
        this.queryParams.pageNum = 1; //默认页数
        this.queryParams.pageSize = 100; //默认条数

        this.undataAddSee(node[0].sortId).then(() => {
          this.isHeight = true; //打开分类树高亮
          this.packingForm = ""; //主计量为空
          this.queryParams.sortId = node[0].sortId; //赋值sortId用于搜索
          this.getMaterialList(); //重新拉取数据
        })
      },
      // 查询所有
      checkleAll() {
        //清空搜索信息，避免干扰
        this.queryParams.sortId = "";
        this.queryParams.code = "";
        this.queryParams.name = "";
        this.printName = "";
        this.queryParams.type = true;
        this.serchReset(); //重置搜索表单
        this.isHeight = false; //关闭分类树高亮
        this.getMaterialList()
      },

      //搜索物料
      search() {
        if (this.searchForm.searchName == "" && this.searchForm.searchCode == "") {
          this.msgError("物料编码或物料名称不能同时为空！");
        } else {
          this.queryParams.name = this.searchForm.searchName; //赋值物料名称
          this.queryParams.code = this.searchForm.searchCode; //赋值物料编码
          this.queryParams.type = true; //查询类型为模糊查询
          this.queryParams.sortId = ""; //避免当分类树点击时页面缓存的sortId导致搜索失败
          this.getMaterialList();
        }

      },

      //查看物料
      seeMaterial(row) {
        this.getPacking().then(() => { //确保已获取主计量成功
          this.star = true;
          this.materialForm = Object.assign({}, row) //拷贝物料信息
          this.undataAddSee(row.sortId).then(() => {
            seeMaterial(row.uniqueId).then(res => {
              if (res.code == 200) {
                // 格式化4位小数
                let basicMount = JSON.parse(JSON.stringify(res.data))
                basicMount.mp = this.Decimal(basicMount.mp);
                basicMount.om = this.Decimal(basicMount.om);
                basicMount.po = this.Decimal(basicMount.po);
                basicMount.prs = this.Decimal(basicMount.prs);
                basicMount.pu = this.Decimal(basicMount.pu);
                basicMount.quantity = this.Decimal(basicMount.quantity);
                basicMount.available = this.Decimal(basicMount.available);
                this.materialMount = basicMount;
              }
            }).catch(err => {
              this.msgError("获取数量信息失败");
            })
            this.open = true;
            this.packingForm = row.unitCode;
            this.dialogTitle = "物料信息";
          })
        })
      },

      // 新增/修改/查看公共获取分类回显
      undataAddSee(id) {
        return new Promise((resolve, reject) => {
          let parentArr = [], //用于储存父类分类信息
            childrenArr = []; ////用于储存子类分类信息
          getEcho(id, this.sortTree, parentArr, childrenArr).then((res) => {
            setTimeout(() => {
              let success = [];
              for (let i = 0; i < res.length; i++) {
                if (success.indexOf(res[i]) === -1) {
                  success.push(res[i])
                }
              }
              let getNode = JSON.parse(JSON.stringify(success)) //拷贝vuex信息，避免影响源数据
              getNode.forEach(v => {
                if (v.ancestors.indexOf(",") > -1) { //是否是子分类
                  v.ancestors = v.ancestors.split(",").length; //拼接数组长度，用于排序
                } else {
                  v.ancestors = 1;
                }
              })
              getNode.sort((a, b) => { //排序得到正常的分类顺序，用于得到sortCode
                return a.ancestors - b.ancestors
              })
              let getCode = [];
              getNode.forEach(code => {
                getCode.push(code.sortCode);
                this.materialForm.sortId = code.sortId
              })
              this.value = getCode; //对话框分类回显

            }, 0)
          });
          resolve()
        })
      },

      // 关闭弹框
      closeDialog() {
        this.resetDilog();
        this.resetSelector();
      },

      //解决级联选择器回显高亮异常问题
      resetSelector() {
        if (this.$refs.classTree) {
          this.$refs.classTree.$refs.panel.activePath = [];
          this.$refs.classTree.$refs.panel.calculateCheckedNodePaths();
        }
      },

      //搜索表单重置
      serchReset() {
        for (let key in this.searchForm) {
          this.searchForm[key] = ""
        }
      },

      // 弹框新增清空表单
      resetFrom() {
        this.materialForm.name = ""; //物料名称清空
        this.materialForm.attribute = ""; //型号规格清空
        this.materialForm.initial = ""; //期初数量清空
        this.materialForm.price = ""; //期初单价清空
        this.materialForm.place = ""; //货位清空
        this.packingForm = ""; //主计量清空
        this.materialMount = {}
      },

      selectClose() {
        this.number = 0;
        this.basicfileList.forEach(value => {
          value.background = false;
        })
        this.continuityStatus = false;
        this.$emit("selectClose");
      },

      // 弹框叉号关闭
      resetDilog() {

          this.value = []; //重置分类
          this.materialForm.code = "";

        this.keepName = false;
        this.keepPeriod = false;
        this.resetFrom();
      },

      //弹框取消
      cancel() {
        this.open = false;
        this.resetDilog()
      },

    },

    components: {
      Tree,

    },
    watch: {
      sortArrId: {
        handler(newData) {
          this.getTreeList();
        },
        deep: true
      }
    }
  };
</script>
<style lang="scss">
  .el-table {
    overflow: inherit;
  }

  // 内层弹框
  .material-in-dialog {
    .el-form-item--medium .el-form-item__label {
      font-size: 13px;
    }

    .ma-right {
      .el-form-item {
        display: flex;
        align-items: center;
        justify-content: flex-end;
      }

      label {
        width: auto;
        flex-grow: 1;
      }

      .el-form-item__content {
        margin-left: 0px !important;
        margin-right: 0 !important;
      }
    }

    .el-cascader--medium {
      width: 100%;
    }

    .el-input.is-disabled .el-input__inner {
      color: #333;
    }

    .from-mount {
      padding: 15px;
      margin-right: 15px;
      -webkit-box-shadow: 1px 1px 10px 1px #eee;
      box-shadow: 1px 1px 10px 1px #eee;
      border-radius: 5px;
      padding-bottom: 10px;
    }

    .cas-input input {
      color: #1890FF !important;
    }

    .now-stock input {
      color: #1890FF !important;
    }

    .now-actual input {
      color: #13CE66 !important;
    }
  }

  .matrial-dialog-box {
    .el-dialog__body {
      height: calc(100vh - 250px);
    }
    .ma-search{
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .el-table .light-row {
      background-color: #F5F7FA;
    }

    .is-plan {
      background: #67c23a !important;
      border-color: #67c23a !important;
      color: #FFFFFF !important;
      outline: none !important;
    }


    .matrial-box {
      .app-container {
        padding-top: 0;
      }

      .el-table__body {
        user-select: none;
      }

      .basicfile-box {
        .el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content {
          color: #1890FF;
        }

        .el-table .el-table__header-wrapper th,
        .el-table .el-table__fixed-header-wrapper th {
          height: 35px;
        }

        .el-table__header,
        .el-table .cell,
        .basicfile-box .has-gutter th,
        .el-table thead {
          overflow: inherit !important;
        }

        // 下拉收起动画
        .toggle-fade {
          transition: all .1s linear;
          overflow: hidden;
        }

        .toggle-fade-enter-active {
          animation: downOpen .2s linear;
          overflow: hidden;
        }

        .toggle-fade-leave-active {
          animation: downOpen .2s reverse linear;
          overflow: hidden;
        }

        @keyframes downOpen {
          from {
            height: 0px;
          }

          to {
            height: 60px;
          }
        }

        .el-table tr td {
          cursor: pointer;
        }

        .has-gutter th:nth-of-type(7) {
          border-right: none;
        }

        .el-table__body-wrapper tr td:nth-of-type(7) {
          border-right: none;
        }

        .txt-right {
          input {
            text-align: right;
          }
        }

        .el-table__header-wrapper,
        .el-table__footer-wrapper {
          overflow: inherit;
        }

        .operation-btn {
          .is-disabled {
            span {
              font-weight: 700;
            }
          }


        }

        .basicfile-box .el-table--medium th,
        .basicfile-box .el-table--medium td {
          overflow: inherit;
        }

        .el-table th>.cell {
          overflow: inherit;
          position: relative;
        }

        .caret-wrapper {
          position: absolute;
          right: 64px;
          top: -5px;
          display: none;
        }

        .el-button--info.is-plain.is-disabled {
          color: #adaeaf;
        }

        .search-box {

          .search-header {
            display: flex;
            align-items: center;
            justify-content: center;

            span {
              width: 65px;
              display: inline-block;
              flex-shrink: 0
            }

            .el-input--mini .el-input__inner {
              padding-right: 10px;
              padding-left: 10px;
            }

            i {
              font-size: 14px;
              cursor: pointer;

            }

            .el-icon-close {
              font-size: 15px;
              color: #999;
            }
          }

          .box-input {
            position: absolute;
            top: 30px;
            z-index: 999;
            left: 0px;
            right: 0px;
            background: #fff;
            height: 60px;
            box-shadow: 1px 1px 5px #eee;

            .input-t {
              padding: 15px;
            }
          }
        }

        .cas-input input {
          color: #1890FF !important;
        }

        .keep-status {
          margin-top: 15px;
        }

        .updata-time {
          input {
            border: none;
          }

        }

        .el-cascader .el-input .el-input__inner {
          color: #1890ff;
        }

        .el-input--suffix input {
          color: #1890FF;
        }

        .el-cascader--medium {
          width: 100%;
        }

        .has-gutter th {
          text-align: center;
          overflow: inherit;
        }

        .el-table--medium th,
        .el-table--medium td {
          padding: 5px 0;
        }
        .el-dialog__body {
          padding-right: 15px;
          padding-bottom: 20px;

        }

        .now-stock {
          input {
            color: #1890FF !important;
          }
        }

        .now-actual input {
          color: #13CE66 !important;
        }

        .el-input.is-disabled .el-input__inner {
          color: #333;
        }

        .el-form-item--medium .el-form-item__content {
          margin-right: 10px;
        }

        .cell {
          padding-right: 14px !important;
          padding-left: 14px !important;

          .basic-delete {
            color: #f56c6c;
          }


          .basic-see {
            color: #67c23a;
          }

          button:hover i {
            font-weight: 700;
          }

          button:hover span {
            font-weight: 700;
          }
        }

        .from-mount {
          padding: 15px;
          margin-right: 15px;
          box-shadow: 1px 1px 10px 1px #eee;
          border-radius: 5px;
          padding-bottom: 10px;

          h3 {
            font-weight: normal;
            font-size: 15px;
            margin-top: 0;
            text-align: center;
            color: #1890ff;
          }
        }

        .foot-bot {
          text-align: inherit !important;
          display: flex;
          justify-content: space-between;
          align-items: center;

          .foot-star {
            color: #1682e6;

            label {
              font-weight: normal;
              font-size: 12px;
            }
          }

        }
      }
    }
  }
</style>
